/********************************************************************************************
*
*   THIS CODE IS NOT APPROVED FOR USE IN/ON ANY OTHER UI ELEMENT OR PRODUCT COMPONENT.
*   Copyright (c) 2011 Aleksey Glukharev
*
********************************************************************************************/

//----------------------------------------
// Global variables
//---
var forums_data = new Array();
var forums_tree = new Array();

//----------------------------------------
// Enable crossdomain interaction
//---
jQuery.support.cors = true;

//----------------------------------------
// Script entry point
//---
$(document).ready(function () {
    System.Gadget.onSettingsClosing = settingsClosing;
    
    // Create tabs
    $("#tabs").tabs({
        select: function (event, ui) {
            // Fill the tree forums takes a long time,
            // so start working with a tree only at the first
            // reference to the tab. The next switching ignored
            if (($(ui.panel).attr("id") == "releases") && ($(ui.panel).data("once") == undefined)) {
                $(ui.panel).data("once", "true")
                loadForumsList();
            }
        }
    });
    
    setUIState();
});

//----------------------------------------
// Handlers
//---
function settingsClosing(event) {
    if (event.closeAction == event.Action.commit) {
        // Save the settings
        writeSettings('defaultSearchType', $("#search-type").val());
        writeSettings('dataRefreshPeriode', $("#data-refresh-periode").val());
        writeSettings('panelsTogglePeriode', $("#panels-toggle-periode").val());
        writeSettings('lastNewsPeriode', $("#last-news-periode").val());
        writeSettings('widgetSkin', $("#skin-name").val());
        
        // If the tree is ready, process it
        if ($("#forums").is(":visible")) {
            // Get a list of the selected forums
            var ids = "";
            $("#forums").jstree("get_checked", null, true).each(function (index) {
                ids += ((index > 0)? "|": "") + $(this).attr("id");
            });
            
            writeSettings("forumsList", ids);
        }
    }
}

//----------------------------------------
// Initialisation functions
//---
function setUIState() {
    var panelsTogglePeriode = readSettings('panelsTogglePeriode');
    $("#panels-toggle-periode option[value='" + panelsTogglePeriode + "']").attr("selected", "selected");
    
    var defaultSearchType = readSettings('defaultSearchType');
    $("#search-type option[value='" + defaultSearchType + "']").attr("selected", "selected");
    
    var dataRefreshPeriode = readSettings('dataRefreshPeriode');
    $("#data-refresh-periode option[value='" + dataRefreshPeriode + "']").attr("selected", "selected");
    
    var lastNewsPeriode = readSettings('lastNewsPeriode');
    $("#last-news-periode option[value='" + lastNewsPeriode + "']").attr("selected", "selected");
    
    var widgetSkin = readSettings('widgetSkin');
    $("#skin-name option[value='" + widgetSkin + "']").attr("selected", "selected");
}

//----------------------------------------
// Working with DOM
//---
function buildTree(parent_id, parent_node) {
    // Process the descendants array
    for (var c = 0; c < forums_tree[parent_id].length; c++) {
        var item_id = forums_tree[parent_id][c];
        
        // Create a child node "li"
        var li = $("<li>", {
            "id": item_id,
            html: $("<a>", {
                html: forums_data[item_id].forum_name,
                "title": forums_data[item_id].forum_name,
                click: function (event) {
                    event.preventDefault();
                }
            })
        })
        .appendTo($(parent_node));
        
        // Is a child itself in the list of parents?
        if (forums_tree[item_id] != undefined) {
            // Child is a parent, start the recursion by adding a new parent
            var ul = $("<ul>").appendTo($(li));
            buildTree(item_id, ul);
        } else {
            // Child is not among the parents - thus he has no children
        }
    }
}

//----------------------------------------
// Ajax functions
//---
function loadForumsList() {
    $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeLoading'] + "</p></span></span>");
    
    $.ajax({
        cache: false,
        type: "POST",
        url: "http://www.nntt.org/ajax.php",
        data: {
            action: "latest_torrents", "get_forums": true, count: 1
        },
        dataType: "json",
        error: function (error) {
            $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/error.png' class='gadget-icon'/>" + strings[ 'error'] + error.statusText + "</p></span></span>");
        },
        success: function (msg) {
            $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeDataPrepare'] + "</p></span></span>");
            
            if (msg.forums != undefined && msg.forums.length > 0) {
                for (var i = 0; i < msg.forums.length; i++) {
                    
                    // Fill the array with the data
                    forums_data[msg.forums[i].forum_id] = {
                        "forum_id": msg.forums[i].forum_id,
                        "parent_id": msg.forums[i].parent_id,
                        "forum_name": msg.forums[i].forum_name
                    }
                    
                    // Fill the array "parent-children"
                    if (forums_tree[msg.forums[i].parent_id] == undefined) {
                        forums_tree[msg.forums[i].parent_id] = new Array();
                    }
                    forums_tree[msg.forums[i].parent_id].push(msg.forums[i].forum_id);
                }
                
                // Root element of the tree
                $("<ul>", {
                    html: $("<li>", {
                        "id": "0",
                        html: $("<a>", {
                            html: strings[ 'allForums'],
                            click: function (event) {
                                event.preventDefault();
                            }
                        })
                    })
                    .append($("<ul>", {
                        id: "root-item"
                    }))
                })
                .appendTo($("#forums"));
                
                // Now process the structure recursively
                buildTree(0, $("#root-item"));
                
                // Now build tree
                $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeBuilding'] + "</p></span></span>");
                $("#forums")
                .bind("loaded.jstree", function (e) {
                    $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeConfig'] + "</p></span></span>");
                    
                    // Try to load a saved forum's list
                    var forumsList = readSettings("forumsList")

                    // Now parse the downloaded list and select checkboxes according it
                    var forumsArray = forumsList.split("|");
                    for (var i = 0; i < forumsArray.length; i++) {
                        $("#forums").jstree("check_node", $("#" + forumsArray[i]));
                    }
                    
                    // We are ready to show tree now
                    $("#forums-loading-info").hide();
                    $(this).show();
                })
                .jstree({
                    core: {
                        animation: 0,
                        initially_open:[ "#0"]
                    },
                    themes: {
                        theme: "default",
                        url: "css/themes/default/style.css",
                        icons: false
                    },
                    checkbox: {
                        two_state: true,
                        override_ui: true,
                        checked_parent_open: false
                    },
                    contextmenu: {
                        items: function (node) {
                            // Menu is only available if there is subforums
                            if ($(node).is(":has(ul)")) {
                                return {
                                    "selectAll": {
                                        "label": strings[ 'selectAll'],
                                        "action": function (obj) {
                                            this.check_node(obj);
                                            this.check_node($(obj).find("li"));
                                        }
                                    },
                                    "unselectAll": {
                                        "label": strings[ 'unselectAll'],
                                        "action": function (obj) {
                                            this.uncheck_node(obj);
                                            this.uncheck_node($(obj).find("li"));
                                        }
                                    }
                                }
                            } else {
                                return;
                            }
                        }
                    },
                    plugins:[ "themes", "html_data", "checkbox", "ui", "contextmenu"]
                });
            }
        }
    });
}